package com.zhixin.zhixinwaimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhixin.zhixinwaimai.common.R;
import com.zhixin.zhixinwaimai.dto.DishDto;
import com.zhixin.zhixinwaimai.entity.Category;
import com.zhixin.zhixinwaimai.entity.Dish;
import com.zhixin.zhixinwaimai.entity.DishFlavor;
import com.zhixin.zhixinwaimai.service.CategoryService;
import com.zhixin.zhixinwaimai.service.DishFlavorService;
import com.zhixin.zhixinwaimai.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    //新增菜品
    @PostMapping
    public R<String> savedish(@RequestBody DishDto dishDto){
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage  = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //模糊条件查询（如果name不为空，就是前端通过name查询菜品）
        dishLambdaQueryWrapper.like(name!=null,Dish::getName,name);
        //根据更新时间排序
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,dishLambdaQueryWrapper);
        //将page<Dish>拷贝成Page<DishDto>,排除records，records是dish对象的集合，我们现在需要dto对象的集合
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtoList=new ArrayList<>();
        for (Dish dish:records) {
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            dishDtoList.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }
    //根据id查询菜品信息和对应的口味信息回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByidWithFlavor(id);
        return R.success(dishDto);
    }
    //保存修改，更新dish表和dishflavor表
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }
//    @GetMapping("/list")
//    public R<List<Dish>> getDishList(Dish dish){//用dish可以接收，而且更通用，以后传个其他属性也能接受
//        Long categoryId = dish.getCategoryId();
//        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        //只查状态为启售的菜品
//        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
//        dishLambdaQueryWrapper.eq(Dish::getCategoryId,categoryId);
//        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);
//        return R.success(dishList);
//    }
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish) {

    List<DishDto> dishDtoList=null;
//动态构造Key
    String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//先从redis中获取缓存数据
    dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
    if(dishDtoList!=null){
        //如果存在，则直接返回，无需查询数据库
        return R.success(dishDtoList);
    }
    //构造查询条件
    LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    //添加条件，查询状态为1的（起售状态）
    lambdaQueryWrapper.eq(Dish::getStatus, 1);
    lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
    //条件排序条件
    lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

    List<Dish> list = dishService.list(lambdaQueryWrapper);

    dishDtoList = list.stream().map((item) -> {
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(item, dishDto);
        Long categoryId = item.getCategoryId();
        //根据id查分类对象
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }

        //当前菜品id
        Long dishId = item.getId();
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishId);
        //SQL: select* from dishflavor where dish_id=?;
        List<DishFlavor> dishFlavorlist = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(dishFlavorlist);
        return dishDto;
    }).collect(Collectors.toList());

    //如果不存在，则查询数据库，并且将查询到的菜品数据添加到缓存中
    redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
    return R.success(dishDtoList);
}

}
